package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "http://localhost:5173") // 允许前端访问
public class  UserController {
    @Autowired
    private UserService userService;

    // 获取所有用户
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    // 根据ID获取用户
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        Optional<User> user = userService.getUserById(id);
        if (user.isPresent()) {
            return ResponseEntity.ok(user.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 创建用户
    @PostMapping
    public User createUser(@RequestBody User user) {
        // 确保username字段被设置
        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            user.setUsername(user.getRealName()); // 使用真实姓名作为默认用户名
        }
        return userService.saveUser(user);
    }

    // 更新用户
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        Optional<User> user = userService.getUserById(id);
        if (user.isPresent()) {
            User updatedUser = user.get();
            // 只有当userDetails中的字段不为null时才更新
            if (userDetails.getPassword() != null) {
                updatedUser.setPassword(userDetails.getPassword());
            }
            if (userDetails.getRealName() != null) {
                updatedUser.setRealName(userDetails.getRealName());
            }
            if (userDetails.getGender() != null) {
                updatedUser.setGender(userDetails.getGender());
            }
            if (userDetails.getRole() != null) {
                updatedUser.setRole(userDetails.getRole());
            }
            if (userDetails.getAvatarUrl() != null) {
                updatedUser.setAvatarUrl(userDetails.getAvatarUrl());
            }
            if (userDetails.getStatus() != null) {
                updatedUser.setStatus(userDetails.getStatus());
            }
            // 新数据库中users表去掉了deleted_at字段
            // if (userDetails.getDeletedAt() != null) {
            //     updatedUser.setDeletedAt(userDetails.getDeletedAt());
            // }
            if (userDetails.getLastLoginTime() != null) {
                updatedUser.setLastLoginTime(userDetails.getLastLoginTime());
            }
            updatedUser.setUpdatedAt(java.time.LocalDateTime.now());
            userService.saveUser(updatedUser);
            return ResponseEntity.ok(updatedUser);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        Optional<User> user = userService.getUserById(id);
        if (user.isPresent()) {
            userService.deleteUser(id);
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据真实姓名获取用户
    @GetMapping("/realName/{realName}")
    public ResponseEntity<User> getUserByRealName(@PathVariable String realName) {
        Optional<User> user = userService.getUserByRealName(realName);
        if (user.isPresent()) {
            return ResponseEntity.ok(user.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据角色获取用户
    @GetMapping("/role/{role}")
    public List<User> getUsersByRole(@PathVariable User.Role role) {
        return userService.getUsersByRole(role);
    }

    // 根据状态获取用户
    @GetMapping("/status/{status}")
    public List<User> getUsersByStatus(@PathVariable User.Status status) {
        return userService.getUsersByStatus(status);
    }
}